import {
  ForwardedRef,
  forwardRef,
  memo,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Control, Controller, UseFormTrigger, useWatch } from 'react-hook-form';
import {
  Button,
  Col,
  Form,
  FormItemProps,
  Input,
  InputProps,
  InputRef,
  message,
  Row,
} from 'antd';
import { PasswordProps } from 'antd/es/input';
import { COUNTDOWN, LEFTTIME } from '@/constants';
import { phoneRegexString } from '@/constants/regexp';
import QueueAnim from 'rc-queue-anim';
import { useSendSmsApi } from '@/hooks/api/useAuthApi';
import { formatCountDown, formatPhone } from '@/utils/format';
import {session} from '@/utils/storage';
import {useRxCountDown} from "@/hooks/useRxCountDown";

const RxCodeInput = forwardRef<
  any,
  PropsWithChildren<
    {
      name: string;
      control: Control<any>;
      item?: FormItemProps;
      triggerName?: any;
      trigger:
        | UseFormTrigger<API.LoginPhoneParams>
        | UseFormTrigger<API.PhoneRegisterParams>
    } & Partial<InputProps>
  >
>(({ triggerName = "phone", trigger, name, control, item, ...rest }, ref) => {
  const animateConfig = [{ opacity: [1, 0], translateY: [0, 5] }];
  const phone = useWatch({ control, name: triggerName });
  const isDisableButton = useMemo(() => {
    return !phoneRegexString.test(phone);
  }, [phone]);

  const { runAsync } = useSendSmsApi();

  const onCodeClickHandler = useCallback(() => {
    setLeftTime(LEFTTIME);
    runAsync({ phone: formatPhone(phone) }).then(() => {
      message.success('发送短信成功');
    });
  }, [phone]);

  const {setLeftTime,countdown} = useRxCountDown()

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState }) => (
        <div ref={ref}>
          <Form.Item {...item}>
            <Row justify={'space-between'}>
              <Col span={13}>
                <Input
                  onFocus={async () => {
                    await trigger(triggerName);
                  }}
                  {...field}
                  {...rest}
                />
              </Col>
              <Col span={9}>
                <Button
                  onClick={onCodeClickHandler}
                  block
                  disabled={isDisableButton || countdown > 0}
                >
                  获取验证码
                  {countdown > 0 ? (
                    <div
                      className={
                        'absolute text-green-500/80  flex-justify-items-center inset-0 bg-gray-300/70'
                      }
                    >
                      <strong className={'tracking-widest'}>重发</strong>(
                      <strong> {formatCountDown(countdown)}s </strong>)
                    </div>
                  ) : null}
                </Button>
              </Col>
            </Row>
            <QueueAnim animConfig={animateConfig}>
              {fieldState.error && (
                <p
                  className={'absolute leading-6 text-xs text-red-400'}
                  key={fieldState.error.message}
                >
                  {fieldState.error?.message}
                </p>
              )}
            </QueueAnim>
          </Form.Item>
        </div>
      )}
    />
  );
});

export default memo(RxCodeInput);
